package com.lwd.util;

import org.apache.commons.beanutils.BeanUtils;

import java.util.ArrayList;
import java.util.List;

public class EnhancedBeanUtil {


    public static <S, D> D createAndCopy(S source, Class<D> clazz) {
        try {
            D newOne = clazz.newInstance();
            // FBI WARNING 不能修改这个BeanUtils的引用！绝对不行！公司内部的BeanUtils拷贝有缺陷！不能拷贝父类数据！反正绝对不能换引用！
            org.apache.commons.beanutils.BeanUtils.copyProperties(newOne, source);
            return newOne;
        } catch (Exception e) {
            throw new IllegalStateException("拷贝数据错误！source="+source+"class="+clazz, e);
        }
    }

    public static <S, D> List<D> createAndCopyList(List<S> source, Class<D> clazz) {
        List<D> dest = new ArrayList<>(source.size());
        for (S s : source) {
            dest.add(createAndCopy(s, clazz));
        }
        return dest;
    }

    public static <S, D> void copyProperties(S source, D dest) {
        // 这个方法有缓存，应该会快一些
        try {
            BeanUtils.copyProperties(dest, source);
        } catch (ReflectiveOperationException e) {
            throw new IllegalStateException("反射调用失败！", e);
        }
    }


}
